'''
Created on 16.10.2012

@author: doleynik
'''
import time
import json

import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import account, subaccount, immeuble
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class Accounts(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(Accounts, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {'code': _('Code'), 'name': _('Title'), 'account': _('Account')}
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
            'title': _('Subaccounts'),
            'header': _('Subaccounts'),
            'immeuble': imm,
            'accounts': account.all(),
            'app_user': self.au,
            'lurl': users.create_logout_url('/'),
            'section': 'parametrage',
            'leftmenu': 'subaccounts',
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/subaccounts.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        accounts = account.all()
        subaccts = imm.get_subacc_list()
        sa = []
        for a in accounts:
            sa.append(['acc', a.code, a.name, '', ''])
            for s in subaccts:
                if s.account.key() == a.key():
                    sa.append(['sacc', s.code, s.name, '' , str(s.key())])
        
        ret = {}
        ret['aaData'] = sa
        self.response.out.write(json.dumps(ret))
    
    def op_list_names_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        subaccts = imm.get_subacc_list()
        sa = []
        for s in subaccts:
            sa.append(str(s.code) + ' ' + str(s.name))
        
        self.response.out.write(json.dumps(sa))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        AccountForm = model_form(subaccount, exclude=['lastchange_by', 'immeuble', 'balance'])
        form = AccountForm()
        
        if self.request.method == 'GET':
            form = AccountForm()
        
        if self.request.method == 'POST':
            form = AccountForm(self.request.POST)
            
            if form.validate():
                new_acc = subaccount(key_name = form['code'].data + "_" + str(imm.key().id()),
                                       account = form['account'].data, 
                                       immeuble = imm, 
                                       code = form['code'].data, 
                                       name = form['name'].data, 
                                       lastchange_by = self.au
                                       )
                new_acc.put()
                while not new_acc.is_saved():
                    time.sleep(2)
                ok_message = _('Account was added.')
            
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))

    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        acc_id = kwargs.get('acc_id', -1)
        acc = subaccount.get(acc_id)
        
        ok_message = ''
        AccountForm = model_form(subaccount, exclude=['lastchange_by', 'immeuble', 'balance'])
        
        if self.request.method == 'GET':
            form = AccountForm(obj = acc)
        
        if self.request.method == 'POST':
            form = AccountForm(self.request.POST)
            
            if form.validate():
                acc.account = form['account'].data 
                acc.code = form['code'].data 
                acc.name = form['name'].data 
                acc.lastchange_by = self.au 
            
            acc.put()
            ok_message = _('Account was saved.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))

    def op_predefine(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        subaccounts_template = imm.get_prdefine_template("subaccounts")
        
        subaccounts = []
        accounts = account.all()
        for a in accounts:
            subaccounts.append(['acc', a.code, a.name])
            for s in subaccounts_template:
                if a.code == s[0]:
                    subaccounts.append(['sacc', s[1], s[2]])
        
        if self.request.method == 'POST':
            imm.set_predefine_subaccounts(self.au)
            self.redirect(webapp2.uri_for('parametrage_account', imm_id=imm_id, command='list'))
            return
        
        template_values = {
            'title': _('Subaccounts template'),
            'header': _('Set of default subaccounts'),
            'immeuble': imm,
            'table': subaccounts,
            'app_user': self.au,
            'lurl': users.create_logout_url('/'),
            'section': 'parametrage',
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/subaccounts_predefine.html')
        self.response.out.write(template.render(template_values))

